// sub_suzhou/uploadList/uploadList.js
const dayjs = require("dayjs");
Page({

  /**
   * 页面的初始数据
   */
  data: {
    
    bankType : wx.getStorageSync("userInfo").bankType,
    agencyCode: wx.getStorageSync("userInfo").agencyCode,
    createBankId: '',
    allselectCheckbox: false,
    fileName: '',
    pageNum: 1,
    pageSize: 10,
    orderType: 3,
    folderName: '',
    purpose: '',
    startTime: '--',
    endTime: '--',
    dataType: 'start',
    currentDate: '',
    minDate: new Date(2020, 0, 1).getTime(),
    maxDate: new Date(2025, 5, 1).getTime(),
    currentDate2: '',
    minDate2: 0,
    maxDate2: 0,
    // ===================
    numPopIshow: false,
    uploadedIshow: false,
    totalPages: 1,
    multiple: 10,
    prolist: [],
    serach_pro: "",
    loading: true,
    oriProlist: [],
    selectCheckbox: [],
    showCheck: false,
    FilePath: '',
    coverIshow: false,
    UploadIshow: false,
    loadingIsshow: false,
    showORG: false,
    columns: [],
    fileList: [],
    radio: '0',
    delta: 0,
    listQuantity: '名单数量',
    updataTime: '上传时间',
    numPopList: [{
      name: '数量升序',
      type: 1
    }, {
      name: '数量降序',
      type: 2
    }, {
      name: '取消排序',
      type: 3
    }],
    orgOptions: [],
    cascaderValue: '',
    // 选中选项对应的id
    cascaderId: '',
    fullPath: '',
    uploadReadOnly: false,
    option: '',
    ShowMdfpAndZbfp: true,

  },
  //全选
  selectALL() {
    console.log(this.data.selectCheckbox, 'selectCheckbox')
    let map = this.data.prolist.map(item => item.fileName);
    this.setData({
      selectCheckbox: map
    })
    console.log(this.data.selectCheckbox, 'selectCheckbox2')

  },
  goback() {
    console.log('11')
    wx.navigateBack({
      delta: 1
    })
  },
  //撤回
  withdrawAll() {
    let selectCheckbox = this.data.selectCheckbox;
    if (selectCheckbox.length == 0) {
      wx.showToast({
        icon: "none",
        title: "请选择企业",
      });
      return
    } else {
      wx.showModal({
        title: '提示',
        content: '此操作将撤回客户经理走访任务，已走访记录不受影响，，确认撤回吗？',
        success: (res) => {
          if (res.confirm) {
            wx.showLoading({
              title: '撤回中...',
            })
            let params = {}
            params.fileNames = selectCheckbox
            params.opType = 'fileName'
            params.token = wx.getStorageSync('token')
            params.userId = wx.getStorageSync("userInfo").userId
            params.range = 'fileNames'
            getApp().globalData.request(
              '/visit/withdrawOrDeleteByFileNames', params,
              "POST"
            ).then(res => {
              wx.hideLoading()
              if (res.code == 200) {
                wx.showToast({
                  icon: "none",
                  title: "撤回成功",
                });
                this.setData({
                  pageNum: 1,
                  selectCheckbox: [],
                })
                // TODO 暂时改为搜索
                this.goSearch()
              } else {
                wx.showToast({
                  icon: "none",
                  title: res.msg,
                });
              }
            })
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    }
  },
  //追加
  supplement() {
    // 追加至文件夹
    let selectCheckbox = this.data.selectCheckbox;
    if (selectCheckbox.length == 0) {
      wx.showToast({
        icon: "none",
        title: "请选择名单",
      });
      return
    } else if (selectCheckbox.length > 1) {
      wx.showToast({
        icon: "none",
        title: "只能选择一个名单",
      });
      return
    } else {
      let prolist = this.data.prolist;
      let filterElement = prolist.filter(item => item.fileName == selectCheckbox[0])[0];
      if (filterElement) {
        this.setData({
          radio: '0', //单选默认 0
          UploadIshow: true,
          fileList: [],
          folderName: filterElement.fileName, //名单名称默认为空
          purpose: filterElement.purpose, //用途默认为空
          uploadReadOnly: true,
          option: '追加'
        })
      }

    }
  },
  //分配
  assignment() {
    // 追加至文件夹
    let selectCheckbox = this.data.selectCheckbox;
    if (selectCheckbox.length == 0) {
      wx.showToast({
        icon: "none",
        title: "请选择分配名单",
      });
      return
    } else if (selectCheckbox.length > 1) {
      wx.showToast({
        icon: "none",
        title: "只能选择一个名单进行分配",
      });
      return
    } else {

      let prolist = this.data.prolist;
      let filterElement = prolist.filter(item => item.fileName == selectCheckbox[0])[0];
      console.log(filterElement, 'this.data.prolistthis.data.prolist')
      if (filterElement) {
        this.setData({
          radio: '0', //单选默认 0
          UploadIshow: true,
          ShowMdfpAndZbfp: false,
          fileList: [],
          folderName: filterElement.fileName, //名单名称默认为空
          purpose: filterElement.purpose, //用途默认为空
          uploadReadOnly: true,
          option: '追加',
          createBankId: filterElement.createBankId
        })
      }
      console.log(this.data.agencyCode, '对比2', this.data.createBankId, '对比')

    }
  },


  resetCascader() {
    let list = this.data.orgOptions.children
    // 通过list给 columns 数组赋值
    let columns = []
    if (!list || list.length == 0) {
      return;
    }
    list.forEach(item => {
      let para = {}
      para.text = item.text
      para.value = item.value
      para.path = item.path
      columns.push(para)
    })
    this.setData({
      columns: columns,
      radio: '',
      cascaderValue: ''
    })
  },
  deleteCascader() {
    this.resetCascader()
  },
  showORG() {
    this.setData({
      showORG: true
    })
  },
  closeORG() {
    this.setData({
      showORG: false
    })
    this.resetCascader()
  },
  //确定
  confirmORG(e) {
    let columns = this.data.columns
    this.setData({
      showORG: false
    })
    let cascaderValue = this.data.cascaderValue
    let cascaderId = this.data.cascaderId
    let fullPath = this.data.fullPath
    if (!cascaderValue) {
      cascaderValue = this.data.columns[0].text
      cascaderId = this.data.columns[0].value
      fullPath = this.data.columns[0].path
    } else {
      //选中的银行有值但有可能是上一次下钻的值，所以需要判断一下
      columns.filter(i => i.text == cascaderValue).length == 0 ? cascaderValue = columns[0].text : cascaderValue = cascaderValue
      columns.filter(i => i.value == cascaderId).length == 0 ? cascaderId = columns[0].value : cascaderId = cascaderId
      columns.filter(i => i.path == fullPath).length == 0 ? fullPath = columns[0].path : fullPath = fullPath
    }
    this.setData({
      cascaderValue: cascaderValue,
      cascaderId: cascaderId,
      fullPath: fullPath
    })
  },
  //下钻
  drillDown(e) {
    // 下啦选项获取的值
    let columns = this.data.columns
    // 银行的层级元数据
    let orgOptions = this.data.orgOptions;
    // 当前选中银行的名称
    let cascaderValue = this.data.cascaderValue;
    if (!cascaderValue) {
      cascaderValue = this.data.columns[0].text
    } else {
      //选中的银行有值但有可能是上一次下钻的值，所以需要判断一下
      columns.filter(i => i.text == cascaderValue).length == 0 ? cascaderValue = columns[0].text : cascaderValue = cascaderValue
    }
    let drillNode = this.getLeafNodeByname(cascaderValue, orgOptions);
    if (drillNode && drillNode.children && drillNode.children.length > 0) {
      let drills = drillNode.children
      let columns = []
      drills.forEach(item => {
        let para = {}
        para.text = item.text
        para.value = item.value
        para.path = item.path
        columns.push(para)
      })
      this.setData({
        columns: columns
      })
    } else {
      wx.showToast({
        icon: "none",
        title: "无可下钻数据",
      });
    }
  },
  getLeafNodeByname(text, node) {
    if (node.text === text) {
      return node;
    }
    if (node.children) {
      for (let i = 0; i < node.children.length; i++) {
        let leafNode = this.getLeafNodeByname(text, node.children[i]);
        if (leafNode) {
          return leafNode;
        }
      }
    }
  },


  onFinish(e) {
    console.log(e, 'eee')
  },
  onChange(e) {
    //给当前选中的数组赋值
    this.setData({
      cascaderValue: e.detail.value.text,
      cascaderId: e.detail.value.value,
      fullPath: e.detail.value.path
    });
  },
  getORG() {
    let params = {}
    params.token = wx.getStorageSync('token');
    params.userId = wx.getStorageSync("userInfo").userId
    getApp().globalData.request(
      '/corpVisit/getBankTree', params,
      "POST"
    ).then(res => {
      console.log(res, 'res');
      if (res.data.length > 0) {
        let list = res.data[0].children
        if (list.length > 0) {
          // 处理进度
          this.setData({
            orgOptions: res.data[0]
          })
          // 通过list给 columns 数组赋值
          let columns = []
          list.forEach(item => {
            let para = {}
            para.text = item.text
            para.value = item.value
            para.path = item.path
            columns.push(para)
          })
          this.setData({
            columns: columns
          })
        }
      }
    })
  },

  // closeORG onFinish
  goSearch() {
    this.setData({
      prolist: []
    })
    this.getList()
  },
  goOnChange(e) {
    console.log(e, 'ee')
    this.setData({
      fileName: e.detail,
    });
  },
  goEnterList(e) {

    const fileName = e.currentTarget.dataset.filename
    const purpose = e.currentTarget.dataset.purpose
    const createTime = e.currentTarget.dataset.createtime
   
    wx.navigateTo({
      url: `/sub_suzhou/orgList/uploadList?fileName=${fileName}&purpose=${purpose}&createTime=${createTime}`,
    });
  },
  canceloutlogin(e) {
    this.setData({
      numPopIshow: false
    })
  },
  numPopSelect(e) {
    console.log(e)
    if (e.detail.type == 1) {
      this.setData({
        listQuantity: '数量升序',
        orderType: e.detail.type,
        numPopIshow: false,
        // =================
        prolist: [],
        pageNum: 1,
      })
    } else if (e.detail.type == 2) {
      this.setData({
        listQuantity: '数量降序',
        orderType: e.detail.type,
        numPopIshow: false,
        // =================
        prolist: [],
        pageNum: 1,
      })
    } else if (e.detail.type == 3) {
      this.setData({
        listQuantity: '名单数量',
        orderType: e.detail.type,
        numPopIshow: false,
        // =================
        prolist: [],
        pageNum: 1,
      })
    }
    this.getList()

  },
  listqtClick() {
    this.setData({
      numPopIshow: true
    })
  },
  uploadedClick() {
    this.setData({
      uploadedIshow: true,
      dataType: 'start'
    })
  },
  uploadedClose() {
    this.setData({
      uploadedIshow: false
    })
  },
  numPopClose() {
    this.setData({
      numPopIshow: false
    })
  },
  dataClick(e) {
    console.log(e, 'ee')
    this.setData({
      dataType: e.currentTarget.dataset.type
    })
  },
  confirm(e, a, b) {
    console.log(this.data.currentDate, '333')
    console.log(e.detail.newParameter.getTime(), 'EEE')

    this.setData({
      currentDate: e.detail.newParameter.getTime(),
      minDate2: e.detail.newParameter.getTime(),
      maxDate2: e.detail.newParameter.getTime() + 31536000000,
      startTime: dayjs(new Date(e.detail.newParameter.getTime())).format("YYYY-MM-DD"),
      endTime: '--'
    })
    // ======================
  },
  confirm2(e) {
    this.setData({
      currentDate2: e.detail.newParameter.getTime(),
      endTime: dayjs(new Date(e.detail.newParameter.getTime())).format("YYYY-MM-DD"),
    })
  },
  determine() {
    if (this.data.startTime == '--' && this.data.endTime == '--') {
      this.setData({
        updataTime: '上传时间',
        uploadedIshow: false,
        // =================
        prolist: [],
        pageNum: 1,
      })
      this.getList()
    } else {
      if (this.data.startTime != '--' && this.data.endTime != '--') {
        let updataTime = this.data.startTime + '至' + this.data.endTime
        this.setData({
          uploadedIshow: false,
          updataTime: updataTime,
          // =================
          prolist: [],
          pageNum: 1,
        })
        this.getList()
      } else {
        wx.showToast({
          title: '请选择结束时间',
          icon: 'none'
        })
      }
    }

    console.log()

  },
  inputconfirm(name, value) {
    console.log(name, value, '11')
    this.setData({
      folderName: name.detail.value
    })
  },
  purposeInputconfirm(name, value) {
    console.log(name, value, '11')
    this.setData({
      purpose: name.detail.value
    })
  },
  reset() {
    this.setData({
      dataType: 'start',
      currentDate: '',
      minDate: new Date(2020, 0, 1).getTime(),
      maxDate: new Date(2025, 5, 1).getTime(),
      currentDate2: '',
      startTime: '--',
      endTime: '--',
    })
  },
  getList() {
    console.log(this.data.fileName, '1111')
    const params = {
      fileName: this.data.fileName,
      pageNum: this.data.pageNum,
      pageSize: this.data.pageSize,
      orderType: this.data.orderType,
      startTime: this.data.startTime == '--' ? '' : this.data.startTime,
      endTime: this.data.endTime == '--' ? '' : this.data.endTime,
      type: 1,
    }
    console.log(params, 'params')
    getApp().globalData.request(
      '/visit/queryVisitCorpFileGroup', params,
      "POST"
    ).then(res => {
   
      console.log(res, 'res');
      if (res.data.list.length > 0) {
        const list = this.data.prolist.concat(res.data.list)


        // 处理进度
        this.setData({
          prolist: list,
          total: res.data.total
        })

      }
    })
  },
  scrollBottom() {
    if (this.data.prolist.length < this.data.total) {
      // this.onBottom();
      this.setData({
        pageNum: ++this.data.pageNum,
      });
      this.getList();
    }
  },
  updataChange(e) {
    console.log(e)
    this.setData({
      radio: e.detail
    })
    // 分配至分支行
    if (e.detail == '3') {
      // this.setData({
      //   showORG: true
      // });
    }
  },
  onCancel() {

  },
  onConfirm(e) {
    console.log(e)
  },
  selectFile() {
    var that = this
    wx.chooseMessageFile({
      count: 10,
      type: 'file',
      extension: ['.xlsx', '.xls', '.XLSX', '.XLS', 'xlsx', 'xls', 'XLSX', 'XLS'],
      success(res) {
        console.log(res, 'res')
        const tempFilePaths = res.tempFiles
        that.setData({
          fileList: tempFilePaths
        })
        console.log(that.data.fileList, 'fileList')

      }
    })
  },
  startupdata() {

    this.setData({
      UploadIshow: false,
      loadingIsshow: true,
      uploadReadOnly: false,
      option: ''
    })
    let that = this
    let path = ''
    let fzhName = '';
    if (this.data.radio == '3') {
      // 银行的层级元数据
      fzhName = this.data.cascaderValue;
      path = this.data.fullPath
    }
    // 开始上传
    const tempFilePaths = this.data.fileList
    for (var i in tempFilePaths) {
      wx.uploadFile({
        url: 'https://fintech-wx.szjrgzjg.com/api/fileApi/getExcel', //TODO 本地测试用上传服务
        // url: 'http://192.168.0.104:20100/api/fileApi/getExcel', //TODO 本地测试用上传服务
        // url: 'https://fintech-wx.szjrgzjg.com/api/fileApi/getExcel', //上传的服务器地址
        filePath: tempFilePaths[i].path,
        name: 'file',
        formData: {
          'file': tempFilePaths[i].path
        },
        header: {
          token: wx.getStorageSync("token"),
          folderName: encodeURIComponent(that.data.folderName),
          purpose: encodeURIComponent(that.data.purpose),
          fileName: encodeURIComponent(tempFilePaths[0].name),
          importType: that.data.radio,
          branchOrgPath: encodeURIComponent(path),
          branchOrgName: encodeURIComponent(fzhName),
        },
        success: function (resp) {
          that.resetCascader()
          if (resp.data) {
            var data = JSON.parse(resp.data)
            if (data.code == 200) {
              wx.showToast({
                title: '上传成功',
                icon: 'none',
                duration: 1300
              })
              that.setData({
                pageNum: 1,
                prolist: [],
              })
              that.getList()
              // 接口结束 弹窗关闭
              that.setData({
                UploadIshow: false,
                loadingIsshow: false
              })
            } else {
              wx.showToast({
                title: data.msg,
                icon: 'none',
                duration: 2000
              })
              // 接口结束 弹窗关闭
              that.setData({
                UploadIshow: false,
                loadingIsshow: false
              })
            }
          }
        },
        fail: function (err) {
          that.resetCascader()
          console.log(err, '失败')
          // 接口结束 弹窗关闭
          that.setData({
            loadingIsshow: false
          })
        }
      })
    }
  },
  delectFile(item, index) {
    this.data.fileList.pop()
    this.setData({
      fileList: this.data.fileList,
    })
  },
  goDown() {
    wx.downloadFile({
      url: 'https://zx-1311146360.cos.ap-shanghai.myqcloud.com/mini_suzhou/%E8%B5%B0%E8%AE%BF%E5%90%8D%E5%8D%95%E5%AF%BC%E5%85%A5%E6%A8%A1%E7%89%88.xlsx', // 下载url
      success(res) {
        console.log('ressss', res)
        if (res.statusCode == 200) {
          console.log('res.statusCode', res)
          // that.openFileEvs(res)
          wx.shareFileMessage({
            filePath: res.tempFilePath,
            success(data) {
              console.log('转发成功！！！', data)
            },
            fileName: '自定义文件名字' + '测试.xlsx',
            fail: console.error,
          })
        }
      },
      fileName: '导出病例',
      fail: console.error,
    })
  },
  goDown2() {
    var that = this;
    wx.setClipboardData({
      data: "https://zx-1311146360.cos.ap-shanghai.myqcloud.com/mini_suzhou/%E8%B5%B0%E8%AE%BF%E5%90%8D%E5%8D%95%E5%AF%BC%E5%85%A5%E6%A8%A1%E7%89%88.xlsx",
      success: function (res) {

      }
    });

  },
  allSelectChange(e) {
    console.log(e)
    this.data.allselectCheckbox = !this.data.allselectCheckbox
    this.setData({
      allselectCheckbox: this.data.allselectCheckbox
    })
    if (this.data.allselectCheckbox == false) {
      this.data.selectCheckbox = []
      this.setData({
        selectCheckbox: []
      })
      console.log(this.data.selectCheckbox, '取消选中')
    } else {
      let map = this.data.prolist.map(item => item.fileName);
      this.setData({
        selectCheckbox: map
      })
    }
  },
  selectChange(e) {
    this.setData({
      selectCheckbox: e.detail,
    });
  },
  upClick() {
    this.setData({
      radio: '0', //单选默认 0
      UploadIshow: true,
      fileList: [],
      folderName: '', //名单名称默认为空
      purpose: '' //用途默认为空
    })
  },
  temClick() {
    this.setData({
      coverIshow: true
    })
  },
  cancelBtn() {
    this.setData({
      loadingIsshow: false
    })
  },
  closeBtn() {
    this.setData({
      UploadIshow: false,
      uploadReadOnly: false,
      option: ''
    })
  },
  closeBtn2() {
    this.setData({
      coverIshow: false
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log(this.data.bankType,'bankTypebankType')
    this.getList();
    // this.getORG();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    console.log('onReady')
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    console.log('onShow')
    var _this = this;
    let aShow = '';
    //获取存储信息
    wx.getStorage({
      key: 'aShow',
      success: function (res) {
        _this.resetCascader()
        // success
        aShow = res.data;
        if (aShow) {
          _this.setData({
            pageNum: 1,
            pageSize: 10,
          })
          // 获取数据函数
          _this.goSearch()
          //删除本地缓存
          wx.removeStorageSync('aShow')
        }
      }
    })

  },
  showManage() {
    let showCheck = !this.data.showCheck;
    this.setData({
      showCheck: showCheck
    })
    console.log(this.data.showCheck)
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    console.log('onHide')
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    console.log('onUnload')
  },


  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    console.log('onPullDownRefresh')
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    console.log('onReachBottom')
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})